package com.tanhua.sso.controller;

import com.tanhua.sso.service.SmsService;
import com.tanhua.sso.vo.ErrorResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Map;

@RestController
@RequestMapping("user")
@Slf4j
public class SmsController {
    @Autowired
    private SmsService smsService;

    /**
     * 发送验证码短信
     *
     * @param param JSON格式的手机号
     * @return 发送成功:null,发送失败:ResponseEntity(500+ErrorResult)
     */
    @PostMapping("login")
    public ResponseEntity<ErrorResult> sendCheckCode(@RequestBody Map<String, String> param) {//@RequestBody主要用来接收前端传递给后端的Json字符串中的数据的(请求体中的数据)
        ErrorResult errorResult;
        String phone = param.get("phone");
        try {
            errorResult = this.smsService.sendCheckCode(phone);//默认短信发送成功,返回null
            if (null == errorResult) {
                return ResponseEntity.ok(null);
            }
        } catch (Exception e) {
            log.error("短信验证码发送失败---phone:" + phone, e);
            errorResult = ErrorResult.builder().errCode("000002").errMessage("验证码短信发送失败").build();
        }
        return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(errorResult);//发送失败就返回500

    }
}
